const express = require("express");
const cors = require("cors");
const handleGlobalError = require("./middleware/handleGlobalError");
const bodyParser = require("body-parser");
const router = require("./router/index"); //导入自己写的router.js
const appConfig = require("./config/config");
const { CloseMysqlConn, CreateMysqlConn } = require("./dao/mysql");
const path = require("path");

const app = express();
CreateMysqlConn();
// 跨域配置, 通过使用cors中间件
app.use(
  cors({
    credentials: true,
    // 动态设置客户端请求过来的域都允许跨域. 直接设置*有问题!!!
    origin: function (req, callback) {
      callback(null, { origin: req });
    },
    allowedHeaders: ["Content-Type", "Authorization"],
  })
);

// 配置body-parse后，request就会多一个body属性来获取post请求数据了
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.engine("html", require("express-art-template"));
app.set("views", path.join(__dirname, "templates"));

//公开目录
// app.use("/public/",express.static("./public/"))

//把路由容器挂载到app服务上来
//注意：配置模板引擎和用body-parser中间件，要在挂载路由之前
app.use(router);

//定时日报
const { sendDaily } = require("./scheduleTask/scheduleDaily");
sendDaily(1);

//全局错误兜底
app.use(handleGlobalError);

app.listen(appConfig.port, function () {
  console.log(`当前服务端运行环境：${appConfig.mode}`);
  console.log(`服务端正在${appConfig.port}端口运行...`);
});

process.on("SIGINT", (code) => {
  CloseMysqlConn();
});
